<template>
  <div>
    <el-upload
      :class="$style.upload"
      :action="imgUploadApi"
      multiple
      accept="image/png, image/jpeg, image/gif"
      :show-file-list="isShowFileList"
      :on-success="updalodOnSuccess"
      :before-upload="updalodBeforeUpload"
      :file-list="fileList"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif文件，且不超过500kb</div>
    </el-upload>
    <el-row>
      <el-col :xs="24" :sm="24" :md="18" :lg="20">
        <el-card
          :body-style="{ padding: '0px' }"
          :class="$style.card"
          v-for="item in list.data"
          :key="item.id"
        >
          <div :class="$style.imgWrapper" @click="imgClickHandler(item.url)">
            <img
              :src="item.url"
              :class="$style.cardImg"
            />
            <span :class="['hide', {[$style.selected]: selectedImgs.includes(item.url)}]">
              <i class="el-icon-check"></i>
            </span>
          </div>
          <div class="card-footer">
            <el-popover width="180">
              <el-select
                :value="item.gid"
                @input="val => {groupSelect(val, item.id)}"
                placeholder="请选择"
              >
                <el-option
                  v-for="group in groupList"
                  :key="group.id"
                  :label="group.name"
                  :value="group.id"
                >
                </el-option>
              </el-select>
              <el-button type="text" slot="reference" class="button" :class="$style.cardBtn">分组</el-button>
            </el-popover>
            <el-button type="text" class="button" @click="deleteHandler(item.id)">删除</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="6" :lg="4">
        <el-card class="box-card">
          <div slot="header">
            <el-button type="primary" @click="addCate">新增分组</el-button>
             <div :class="$style.addCateWrapper" v-if="isShowAddCateWrapper">
              <el-input v-model="newCateName" placeholder="请输入内容"></el-input>
              <el-button type="text" @click="confirmAddCate">确认</el-button>
              <el-button type="text" @click="cancelAddCate">取消</el-button>
            </div>
          </div>
          <a
            v-for="(group, index) in groupList"
            :key="group.id"
            :class="[$style.cateItem, {
              [$style.active]: index === currentCateIndex
            }]"
            @click.prevent="cateClickHander(index, group.id)"
          >
            {{group.name}}
            <i
              class="el-icon-close"
              :class="$style.close"
              @click.stop="deleteGroup(group.id, group.name)"
            >
            </i>
          </a>
        </el-card>
      </el-col>
    </el-row>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="currentPageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="list.total">
    </el-pagination>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import * as apis from 'services/gallery'
import api from 'config/api'

export default {
  name: 'Gallery',
  props: {
    openInDialog: {
      type: Boolean,
      default: false,
    },
    max: Number,
    radio: Boolean,
    value: Array,
  },
  computed: {
    ...mapState({
      list: state => state.gallery.list,
      groupList: state => state.gallery.groupList,
    }),
  },
  data() {
    return {
      imgUploadApi: api.getImgUploadApi(),
      currentPage: 1,
      currentPageSize: 20,
      currentCateIndex: 0,
      currentGid: 0,
      newCateName: '',
      isShowAddCateWrapper: false,
      isShowFileList: true,
      fileList: [],
      selectedImgs: this.value || [],
      groupModel: {},
    }
  },
  created() {
    this.$store.dispatch('getImageList', {})
    this.$store.dispatch('getGroupList')
  },
  watch: {
    value(val) {
      this.selectedImgs = val
    },
  },
  methods: {
    imgClickHandler(src) {
      if (!this.openInDialog) {
        return
      }

      if (this.max && this.selectedImgs.length >= this.max) {
        return
      }

      // 单选
      if (this.radio) {
        this.selectedImgs[0] = src
        this.$emit('on-select', this.selectedImgs[0])
      } else {
        if (this.selectedImgs.includes(src)) {
          this.selectedImgs = this.selectedImgs
            .filter(item => item !== src)
        } else {
          this.selectedImgs.push(src)
        }
        this.$emit('input', this.selectedImgs)
        this.$emit('on-select', this.selectedImgs)
      }
    },
    updalodBeforeUpload(file) {
      const isLt500K = file.size / 1024 / 1024 < 0.5
      if (!isLt500K) {
        this.$message.error('上传头像图片大小不能超过 500KB!')
      }
      this.isShowFileList = true
      return isLt500K
    },
    updalodOnSuccess() {
      this.$store.dispatch('getImageList', {})
      setTimeout(() => {
        this.isShowFileList = false
        this.fileList = []
      }, 1000)
    },
    addCate() {
      this.isShowAddCateWrapper = true
    },
    confirmAddCate() {
      if (!this.newCateName) return

      apis.addImgGroup(this.newCateName)
        .then(() => {
          this.isShowAddCateWrapper = false
          this.newCateName = ''
          this.$store.dispatch('getGroupList')
        })
    },
    cancelAddCate() {
      this.isShowAddCateWrapper = false
    },
    handleSizeChange(pageSize) {
      this.currentPageSize = pageSize
      this.$store.dispatch('getImageList', {
        pageSize,
        page: this.currentPage,
        gid: this.currentGid,
      })
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.$store.dispatch('getImageList', {
        page,
        pageSize: this.currentPageSize,
        gid: this.currentGid,
      })
    },
    cateClickHander(index, gid) {
      this.currentCateIndex = index
      this.currentGid = gid
      this.$store.dispatch('getImageList', {
        page: this.currentPage,
        pageSize: this.currentPageSize,
        gid,
      })
    },
    groupSelect(gid, id) {
      this.$store.dispatch('imageGrouping', { gid, id })
    },
    deleteGroup(id, name) {
      this.$confirm(`确认要删除${name}这个分组吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        apis.deleteGroup(id)
      })
      .then(() => {
        this.$store.dispatch('getGroupList')
      })
    },
    deleteHandler(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        this.$store.dispatch('deleteImgById', id)
        this.$message({
          type: 'success',
          message: '删除成功!',
        })
      })
    },
  },
}
</script>

<style module lang="scss">
.upload {
  margin-bottom: 12px;
}

.card {
  width: 180px;
  display: inline-block;
  margin-right: 20px;
  margin-bottom: 20px;
  z-index: 1000;
}

.cardImg {
  width: 100%;
  height: 180px;
}

.cateItem {
  display: block;
  cursor: pointer;
  padding: 10px 6px;
  &:hover {
    background-color: #eef1f6;
  }
  &:not(:first-child):hover {
    .close {
      opacity: 1;
    }
  }
}

.active {
  background-color: #eef1f6;
}

.addCateWrapper {
  padding: 6px 0;
  input {
    margin-bottom: 6px;
  }
}

.imgWrapper {
  position: relative;
}

.selected {
  display: block !important;
  position: absolute;
  width: 100%;
  height: 180px;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, .5);
  text-align: center;
  i {
    color: #f5f5f5;
    line-height: 180px;
    font-size: 50px;
  }
}

.close {
  opacity: 0;
  font-size: 10px;
  float: right;
  padding: 3px;
}

.cardBtn {
  margin-right: 4px;
}
</style>
